from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet

from threedGestureProject.common.result import BaseResponse


class MCreateModelMixin(mixins.CreateModelMixin, GenericViewSet):
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return BaseResponse(data=serializer.data, headers=headers)


class MRetrieveModelMixin(mixins.RetrieveModelMixin, GenericViewSet):
    def retrieve(self, request, *args, **kwargs):
        """
                get /entity/{pk}/
                """
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return BaseResponse(data=serializer.data)


class MUpdateModelMixin(mixins.UpdateModelMixin, GenericViewSet):
    def update(self, request, *args, **kwargs):
        """
                put /entity/{pk}/
                """
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        print(request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return BaseResponse(data=serializer.data)


class MDestroyModelMixin(mixins.DestroyModelMixin, GenericViewSet):
    def destroy(self, request, *args, **kwargs):
        """
                delete /entity/{pk}/
                """
        instance = self.get_object()
        self.perform_destroy(instance)
        return BaseResponse(message='数据删除成功.')


class MListModelMixin(mixins.ListModelMixin, GenericViewSet):
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return BaseResponse(data=serializer.data)
